package pl.edu.mimuw.irs.rcp.controller.editor.bucket;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import pl.edu.mimuw.irs.core.model.analysis.History;
import pl.edu.mimuw.irs.core.model.analysis.Time;
import pl.edu.mimuw.irs.core.model.design.resource.Resource;

public class BucketCalculations {

	// *** Attributes

	private List<History> runs;
	private int size;
	private Integer[] totalCosts;
	private Integer[] totalTimes;
	private Map<String, Integer[]> resourcesCosts;
	private Map<String, Integer[]> resourcesTimes;
	public List<History> getRuns() {
		return runs;
	}
	public int getSize() {
		return size;
	}
	public Integer[] getTotalCosts() {
		return totalCosts;
	}
	public Integer[] getTotalTimes() {
		return totalTimes;
	}
	public Map<String, Integer[]> getResourcesCosts() {
		if (resourcesCosts == null) resourcesCosts = new LinkedHashMap<String, Integer[]>();
		return resourcesCosts;
	}
	public Map<String, Integer[]> getResourcesTimes() {
		if (resourcesTimes == null) resourcesTimes = new LinkedHashMap<String, Integer[]>();
		return resourcesTimes;
	}
	
	// *** Constructors
	
	public BucketCalculations(List<History> runs) {
		if (runs == null) runs = Collections.emptyList();
		
		this.runs = runs;
		size = runs.size();
		
		this.totalCosts = new Integer[size];
		this.totalTimes = new Integer[size];
		
		init();
	}
	
	// *** Methods
	
	public void init() {
		int i = 0;
		
		Map<String, Integer[]> resourcesCosts = getResourcesCosts();
		Map<String, Integer[]> resourcesTimes = getResourcesTimes();
		
		for (History run : getRuns()) {
			totalCosts[i] = run.getTotalUsageCost();
			totalTimes[i] = run.getTimestamp().getValue();
			
			/* Per resource cost */
			Map<Resource, Time> usage = run.getUsage();
			for (Entry<Resource, Time> entry : usage.entrySet()) {
				Resource resource = entry.getKey();
				
				Integer[] costsArray = resourcesCosts.get(resource.toString());
				Integer[] timesArray = resourcesTimes.get(resource.toString());
				
				if (costsArray == null) {
					costsArray = new Integer[getSize()];
					Arrays.fill(costsArray, 0);
					resourcesCosts.put(resource.toString(), costsArray);
				}
				if (timesArray == null) {
					timesArray = new Integer[getSize()];
					Arrays.fill(timesArray, 0);
					resourcesTimes.put(resource.toString(), timesArray);
				}
				
				costsArray[i] = resource.getUnitCost() * entry.getValue().getValue();
				timesArray[i] = entry.getValue().getValue();
			}
			
			i++;
		}
	};
}
